package com.anyikang.volunteer.sos.volunteer.app.mine;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.anyikang.volunteer.sos.volunteer.R;
import com.anyikang.volunteer.sos.volunteer.app.MyConstant;
import com.anyikang.volunteer.sos.volunteer.app.adapter.MyRescueRecordAdapter;
import com.anyikang.volunteer.sos.volunteer.app.bean.MyRescueListData;
import com.anyikang.volunteer.sos.volunteer.app.bean.MyRescueListItem;
import com.anyikang.volunteer.sos.volunteer.app.bean.MyRescueListJson;
import com.anyikang.volunteer.sos.volunteer.app.bean.User;
import com.anyikang.volunteer.sos.volunteer.app.view.MyScrollListView;
import com.anyikang.volunteer.sos.volunteer.app.view.RefreshScrollviewLayout;
import com.anyikang.volunteer.sos.volunteer.utils.MyErrorDeal;
import com.anyikang.volunteer.sos.volunteer.utils.okhttputils_callback.StringDialogCallback;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 我的救援记录
 * @author xw.gao
 * @version 2017/7/11
 */
public class MyRescueActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener,
        RefreshScrollviewLayout.OnLoadListener {

    MyScrollListView lvRecords;
    RefreshScrollviewLayout swipeLayout;
    String TAG = "MyRescueActivity"+"_gxw";
    private ArrayList<MyRescueListItem> mMyRescueList = new ArrayList<MyRescueListItem>();
    MyRescueRecordAdapter mAdapter;
    private View layout;

    private boolean hasNextPage = false;
    private final int REFRESH_LIST = 0;  //刷新列表
    private final int LOAD_MORE = 1;   //加载更多
    int pageIndex = 1;
    int pageSize = 20;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        setContentView(R.layout.activity_my_sos);
        initView();

        Log.i(TAG,"onCreateView");
        super.onCreate(savedInstanceState);
    }

    /**
     * 初始化视图
     */
    private void initView() {

        //标题
        TextView tvTitle = (TextView) this.findViewById(R.id.tv_title);
        tvTitle.setText("我的救援");
        ImageButton imgBtLeft = (ImageButton) this.findViewById(R.id.imgBtLeft);
        imgBtLeft.setOnClickListener(this);


        lvRecords = (MyScrollListView) this.findViewById(R.id.lvMyRecords);
        mAdapter = new MyRescueRecordAdapter(mMyRescueList,this,"");
        lvRecords.setAdapter(mAdapter);
        lvRecords.setOverscrollHeader(getResources().getDrawable(R.mipmap.ic_launcher));

        swipeLayout = (RefreshScrollviewLayout) this.findViewById(R.id.swipe_container);
        swipeLayout.setLoadingLayout((LinearLayout)this.findViewById(R.id.listLayout));
        swipeLayout.setColorSchemeResources(R.color.color_bule,
                R.color.green,
                R.color.color_bule,
                R.color.green_50bc31);
        swipeLayout.setSize(SwipeRefreshLayout.DEFAULT);
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setOnLoadListener(this);
    }

    /**
     * 获得服务端报警记录
     * @param operation
     */
    protected void getData(int operation) {
        getAllRecords(operation);
    }


    /**
     * 获取成功
     */
    public void  dealGetSuccess(MyRescueListData data, int operation) {

        hasNextPage = data.isHasNextPage();

        if (operation == REFRESH_LIST)
        {
            if(mMyRescueList != null)
            {
                mMyRescueList.clear();
                mAdapter.notifyDataSetChanged();
            }
        }

        ArrayList<MyRescueListItem> myRescueListItem =  data.getList();

        if(myRescueListItem!=null && myRescueListItem.size() > 0)
        {
            mMyRescueList.addAll(myRescueListItem);
        }
        mAdapter.notifyDataSetChanged();

        if(hasNextPage)
        {
            //gxw-  hasNextPage = true;
            pageIndex++;
        }
        else {
            //gxw- hasNextPage = false;
        }
        return;

    }
    public void getAllRecords(final int operation)
    {


        User user = new User(MyRescueActivity.this);
        String token = user.getUserToken();
        int state = 0;  //0查询全部,2未完成，3已完成

        Log.i(TAG,"url ="+ MyConstant.API_MY_SOS_LIST + "token="+token+",state="+state+",pageIndex="+pageIndex+",pageSize="+pageSize);
        OkHttpUtils
                .get(MyConstant.API_MY_SOS_LIST)//
                .tag(MyConstant.API_MY_SOS_LIST)//
                .params("tokenId", token)//
                .params("state",String.valueOf(state))
                .params("pageIndex",String.valueOf(pageIndex))
                .params("pageSize",String.valueOf(pageSize))
                .params("sortType",String.valueOf(2))
                .execute(new StringDialogCallback(MyRescueActivity.this) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                        swipeLayout.setLoading(false);
                        swipeLayout.setRefreshing(false);
                        int retCode = response.code();
                        if(retCode == 200)
                        {
                            Log.i(TAG,"onSuccess 200 return："+s);
                            try
                            {
                                MyRescueListJson myRescueListJson = new Gson().fromJson(s,MyRescueListJson.class);

                                if(myRescueListJson.getStatus() == 1)//查询全部成功
                                {
                                    //
                                    dealGetSuccess(myRescueListJson.getData(),operation);
                                }
                                else {
                                    String msg = myRescueListJson.getMsg();
                                    MyErrorDeal.dealError(msg,MyRescueActivity.this);
                                }
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                        }
                        else
                        {
                            MyErrorDeal.dealHttpError(response,MyRescueActivity.this);
                            Log.i(TAG,"onSuccess "+retCode+"return: "+s);
                        }
                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {

                        swipeLayout.setLoading(false);
                        swipeLayout.setRefreshing(false);
                        MyErrorDeal.dealHttpError(response,MyRescueActivity.this);

                    }
                });

        return;
    }
    /**
     * 回到页面自动刷新
     */
    public void autoRefresh()
    {
        swipeLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeLayout.setRefreshing(true);

            }
        });

        pageIndex = 1;
        getData(REFRESH_LIST);//刷新页面


    }

    @Override
    public void onResume() {
        Log.i(TAG,"onResume");
        autoRefresh();
        //gxw- getData(REFRESH_LIST);//刷新页面
        super.onResume();
    }


    @Override
    public void onRefresh() {
        Log.i(TAG,"onRefresh");
         pageIndex = 1;
        getData(REFRESH_LIST);

    }

    @Override
    public void onLoad() {

        Log.i(TAG,"onLoad");
        if(hasNextPage)
        {
            getData(LOAD_MORE);
        }
        else {
            swipeLayout.setLoading(false);
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId())
        {
            case R.id.imgBtLeft:
                MyRescueActivity.this.finish();
                break;
        }

    }

    @Override
    protected void onDestroy() {
        pageIndex = 1;
        hasNextPage = false;
        super.onDestroy();
    }
}
